package com.faner.fast.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.faner.fast.upms.model.SysDeptDO;
import com.faner.fast.upms.model.SysDeptRelationDO;
import com.faner.fast.upms.mapper.SysDeptRelationMapper;
import com.faner.fast.upms.service.SysDeptRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门关系表 服务实现类
 * </p>
 *
 * @author faner
 * @since 2021-01-29
 */
@Service
@RequiredArgsConstructor
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelationDO> implements SysDeptRelationService {
    private final SysDeptRelationMapper sysDeptRelationMapper;

    /**
     * 维护部门关系
     * @param sysDept 部门
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDeptRelation(SysDeptDO sysDept) {
        // 增加部门关系表
        SysDeptRelationDO condition = new SysDeptRelationDO();
        condition.setDescendant(sysDept.getParentId());
        List<SysDeptRelationDO> relationList = sysDeptRelationMapper.selectList(
                Wrappers.<SysDeptRelationDO>query().lambda().eq(SysDeptRelationDO::getDescendant, sysDept.getParentId()))
                .stream().map(relation -> {
                    relation.setDescendant(sysDept.getId());
                    return relation;
                }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(relationList)) {
            this.saveBatch(relationList);
        }

        // 自己也要维护到关系表中
        SysDeptRelationDO own = new SysDeptRelationDO();
        own.setDescendant(sysDept.getId());
        own.setAncestor(sysDept.getId());
        sysDeptRelationMapper.insert(own);
    }

    /**
     * 通过ID删除部门关系
     * @param id
     */
    @Override
    public void removeDeptRelationById(Long id) {
        baseMapper.deleteDeptRelationsById(id);
    }

    /**
     * 更新部门关系
     * @param relation
     */
    @Override
    public void updateDeptRelation(SysDeptRelationDO relation) {
        baseMapper.updateDeptRelations(relation);
    }

}
